﻿@page "/PlotlyBlazorLineChartTest"
@inject IJSRuntime jsRuntime

<h3>PlotlyBlazorLineChartTest</h3>

@using Plotly.Blazor
@using Plotly.Blazor.Traces


<PlotlyChart @ref="plotlyChart" @bind-Data="data"
             @bind-Layout="layout"
             @bind-Config="config" SelectedAction="SelectedAction" RelayoutAction="RelayoutAction" RestyleAction="RestyleAction" AfterRender="Init" />
<Button Text="Add Data" OnClick="AddData" />

<script src="_content/Plotly.Blazor/plotly-3.0.0.min.js"></script>
<script src="_content/Plotly.Blazor/plotly-interop-6.0.0.js"></script>
<script src="./plotlyInterop.js"></script>

@code {
    protected override async Task OnInitializedAsync()
    {
        config = new Config
        {
            Responsive = true,
            Editable = true,
            EditSelection = true,
            Edits = new Plotly.Blazor.ConfigLib.Edits
            {

            },
            //ModeBarButtonsToRemove = new List<string>
            //{
            //    "select2d",
            //    "lassoSelect"
            //},
        };

        layout = new Plotly.Blazor.Layout
        {
            //SelectDirection = Plotly.Blazor.LayoutLib.SelectDirectionEnum.V,
            Title = new Plotly.Blazor.LayoutLib.Title
            {
                Text = "可移动矩形的折线图示例",
            },
            BoxMode = Plotly.Blazor.LayoutLib.BoxModeEnum.Overlay,
            Selections = new[]
            {
                new Plotly.Blazor.LayoutLib.Selection
                {
                     XRef="paper",
                      Name="test",
                       X0=2,
                        X1=3,
                         Y0=1,
                         Y1=2,
                          YRef="paper",
                          Line= new  Plotly.Blazor.LayoutLib.SelectionLib.Line{ Color = "red", Width = 2 },
                          Type= Plotly.Blazor.LayoutLib.SelectionLib.TypeEnum.Rect,
                          //XRef="paper",

                }
                // ,new Plotly.Blazor.LayoutLib.Selection
                //{
                //      Name="test",
                //       X0=1,
                //        X1=2,
                //         Y0=1,
                //         Y1=2,
                //          YRef="y",
                //          Line= new  Plotly.Blazor.LayoutLib.SelectionLib.Line{ Color = "red", Width = 2 },
                //          Type= Plotly.Blazor.LayoutLib.SelectionLib.TypeEnum.Rect,
                //          //XRef="paper",

                //}
            }
            ,
            Shapes = new[]
            {
                new Plotly.Blazor.LayoutLib.Shape
                {
                    Type = Plotly.Blazor.LayoutLib.ShapeLib.TypeEnum.Rect,
                    X0 = 3,  // 初始左边界
                    X1 = 4,  // 初始右边界
                    Y0 = 0,
                    Y1 = 1,
                    YRef = "paper", // 相对 Y 轴范围（0-1）
                    Line = new  Plotly.Blazor.LayoutLib.ShapeLib.Line { Color = "red", Width = 2 },
                    FillColor = "rgba(255,0,0,0.2)",
                     Editable=true,
                },
                new Plotly.Blazor.LayoutLib.Shape
                {
                    Type = Plotly.Blazor.LayoutLib.ShapeLib.TypeEnum.Rect,
                    X0 = 1,  // 初始左边界
                    X1 = 2,  // 初始右边界
                    Y0 = 0,
                    Y1 = 1,
                    YRef = "paper", // 相对 Y 轴范围（0-1）
                    Line = new  Plotly.Blazor.LayoutLib.ShapeLib.Line { Color = "red", Width = 2 },
                    FillColor = "rgba(255,0,0,0.2)",
                     Editable=false,
                      Y0Shift=0,
                       Y1Shift=1,
                }
            }
            ,
            DragMode = Plotly.Blazor.LayoutLib.DragModeEnum.Select,
            XAxis = new[]
              {
                new Plotly.Blazor.LayoutLib.XAxis
                {
                    Title = new Plotly.Blazor.LayoutLib.XAxisLib.Title
                    {
                        Text = "X轴",
                    },
                       FixedRange=true,

                    //Range=new List<object> { 1, 4 },
                }
            },
            YAxis = new[]
            {
                new Plotly.Blazor.LayoutLib.YAxis
                {
                    Title = new  Plotly.Blazor.LayoutLib.YAxisLib.Title
                    {
                        Text = "Y轴",
                    },
                    FixedRange=true,
                    //Range=new List<object> { 1, 4 },
                }
            }
        };


        data = new List<ITrace>
{
            new Scatter
            {
                Name = "ScatterTrace",
                Mode = Plotly.Blazor.Traces.ScatterLib.ModeFlag.Lines | Plotly.Blazor.Traces.ScatterLib.ModeFlag.Markers,
                X = new List<object>{1,2,3},
                Y = new List<object>{1,2,3}
            }
    };
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await jsRuntime.InvokeVoidAsync("import", "./plotlyInterop.js");
        await jsRuntime.InvokeVoidAsync("import", "./_content/Plotly.Blazor/plotly-3.0.0.min.js");
        await jsRuntime.InvokeVoidAsync("import", "./_content/Plotly.Blazor/plotly-interop-6.0.0.js");
        if (firstRender)
        {
            //await jsRuntime.InvokeVoidAsync("initializeDragControl", plotlyChart.Id, DotNetObjectReference.Create(this));
        }
    }

    private bool isUpdating = false; // 防止无限循环
    [JSInvokable]
    public async Task HandleRelayout(Dictionary<string, object> relayoutData)
    {
        if (isUpdating) return;
        isUpdating = true;

        try
        {
            // 如果检测到 Y 坐标变化，强制修正
            if (relayoutData.ContainsKey("shapes[0].y0"))
            {
                // 保留用户修改的 X 坐标
                var newX0 = relayoutData.TryGetValue("shapes[0].x0", out var x0) ? x0 : layout.Shapes[0].X0;
                var newX1 = relayoutData.TryGetValue("shapes[0].x1", out var x1) ? x1 : layout.Shapes[0].X1;

                // 通过 Relayout 方法应用修正后的布局
                await plotlyChart.Relayout(new Dictionary<string, object>
{
                    { "shapes[0].x0", newX0 },
                    { "shapes[0].x1", newX1 },
                    { "shapes[0].y0", 0 }, // 固定 Y0
                    { "shapes[0].y1", 1 }  // 固定 Y1
                });
                this.Init();
            }
        }
        finally
        {
            isUpdating = false;
        }
    }

}
